package org.csu.onlineedubackend.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import org.csu.onlineedubackend.entity.GroupAdmin;
import org.csu.onlineedubackend.entity.GroupMute;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.service.GroupManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/group")
public class GroupManagementController {

    @Autowired
    private GroupManagementService groupManagementService;

    private Integer getUserIdFromRequest(HttpServletRequest request) throws NotLoginException {
        try {
            return StpUtil.getLoginIdAsInt();
        } catch (NotLoginException e) {
            String token = request.getHeader("satoken");
            if (token == null || token.isEmpty()) {
                token = request.getParameter("token");
            }

            if (token != null && !token.isEmpty()) {
                Object loginId = StpUtil.getLoginIdByToken(token);
                if (loginId != null) {
                    return Integer.parseInt(loginId.toString());
                }
            }
            throw new NotLoginException("未登录或登录已过期，请重新登录", e.getType(), e.getLoginType());
        }
    }

    /**
     * 获取群成员列表（包含角色和禁言状态）
     */
    @GetMapping("/{groupId}/members")
    public CommonResponse<List<Map<String, Object>>> getGroupMembers(@PathVariable Long groupId, HttpServletRequest request) {
        try {
            getUserIdFromRequest(request); // Check login status
            List<Map<String, Object>> members = groupManagementService.getGroupMembersWithRoles(groupId);
            return CommonResponse.createForSuccess(10000, "获取群成员列表成功", members);
        } catch (NotLoginException e) {
            System.out.println("11111");
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            System.out.println("22222");
            System.out.println(e);
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 设置群管理员
     */
    @PostMapping("/{groupId}/admin/{userId}")
    public CommonResponse<GroupAdmin> setGroupAdmin(@PathVariable Long groupId, @PathVariable Integer userId,
                                                    @RequestParam Integer currentUserId) {
        try {
            GroupAdmin groupAdmin = groupManagementService.setGroupAdmin(groupId, userId, currentUserId);
            return CommonResponse.createForSuccess(10000, "设置管理员成功", groupAdmin);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 取消群管理员
     */
    @DeleteMapping("/{groupId}/admin/{userId}")
    public CommonResponse<Boolean> removeGroupAdmin(@PathVariable Long groupId, @PathVariable Integer userId,
                                                    @RequestParam Integer currentUserId) {
        try {
            boolean result = groupManagementService.removeGroupAdmin(groupId, userId, currentUserId);
            return CommonResponse.createForSuccess(10000, "取消管理员成功", result);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 获取群管理员列表
     */
    @GetMapping("/{groupId}/admins")
    public CommonResponse<List<User>> getGroupAdmins(@PathVariable Long groupId, HttpServletRequest request) {
        try {
            getUserIdFromRequest(request); // Check login status
            List<User> admins = groupManagementService.getGroupAdmins(groupId);
            return CommonResponse.createForSuccess(10000, "获取管理员列表成功", admins);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 禁言群成员
     */
    @PostMapping("/{groupId}/mute/{userId}")
    public CommonResponse<GroupMute> muteGroupMember(
            @PathVariable Long groupId, 
            @PathVariable Integer userId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date muteUntil,
            @RequestParam Integer currentUserId) {
        try {
            GroupMute groupMute = groupManagementService.muteGroupMember(groupId, userId, currentUserId, muteUntil);
            return CommonResponse.createForSuccess(10000, "禁言成员成功", groupMute);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 取消禁言群成员
     */
    @DeleteMapping("/{groupId}/mute/{userId}")
    public CommonResponse<Boolean> unmuteGroupMember(@PathVariable Long groupId, @PathVariable Integer userId,
                                                     @RequestParam Integer currentUserId) {
        try {
            boolean result = groupManagementService.unmuteGroupMember(groupId, userId, currentUserId);
            return CommonResponse.createForSuccess(10000, "取消禁言成功", result);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 全群禁言
     */
    @PostMapping("/{groupId}/muteall")
    public CommonResponse<GroupMute> muteGroup(
            @PathVariable Long groupId,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date muteUntil,
            @RequestParam Integer currentUserId) {
        
        try {
            GroupMute groupMute = groupManagementService.muteGroup(groupId, currentUserId, muteUntil);
            return CommonResponse.createForSuccess(10000, "全群禁言成功", groupMute);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 取消全群禁言
     */
    @DeleteMapping("/{groupId}/muteall")
    public CommonResponse<Boolean> unmuteGroup(@PathVariable Long groupId, @RequestParam Integer currentUserId) {
        try {
            boolean result = groupManagementService.unmuteGroup(groupId, currentUserId);
            return CommonResponse.createForSuccess(10000, "取消全群禁言成功", result);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 检查用户是否被禁言
     */
    @GetMapping("/{groupId}/mute/check/{userId}")
    public CommonResponse<Boolean> checkUserMuted(@PathVariable Long groupId, @PathVariable Integer userId, HttpServletRequest request) {
        try {
            getUserIdFromRequest(request); // Check login status
            boolean isMuted = groupManagementService.isUserMuted(groupId, userId);
            return CommonResponse.createForSuccess(10000, "检查禁言状态成功", isMuted);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 检查群是否被全体禁言
     */
    @GetMapping("/{groupId}/muteall/check")
    public CommonResponse<Boolean> checkGroupMuted(@PathVariable Long groupId, HttpServletRequest request) {
        try {
            getUserIdFromRequest(request); // Check login status
            boolean isMuted = groupManagementService.isGroupMuted(groupId);
            return CommonResponse.createForSuccess(10000, "检查全群禁言状态成功", isMuted);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
    
    /**
     * 解散群聊
     */
    @DeleteMapping("/{groupId}/disband")
    public CommonResponse<Void> disbandGroup(@PathVariable Long groupId, @RequestParam Integer currentUserId) {
        try {
            groupManagementService.disbandGroup(groupId, currentUserId);
            return CommonResponse.createForSuccess(10000, "群聊解散成功", null);
        } catch (NotLoginException e) {
            return CommonResponse.createForError(e.getMessage());
        } catch (RuntimeException e) {
            return CommonResponse.createForError(e.getMessage());
        }
    }
} 